<?
declare (strict_types = 1);
namespace core;

use Closure;
use Swoole\Timer;

class Task
{
    private $name  = '匿名任务';
    private $space = 0;
    private $after = 0;
    public function name(string $name = '')
    {
        $this->name = $name;
        return $this;
    }
    public function space(float | int $space)
    {
        $this->space = $space;
        return $this;
    }
    public function after(float | int $after)
    {
        $this->after = $after;
        return $this;
    }
    public function call(Closure $call)
    {
        if ($this->space == 0) {
            if ($this->after <= 0) {
                loger('立即执行一次' . $this->name);
                $call();
            } else {
                loger($this->after . '秒后执行一次' . $this->name);
                Timer::after(1000 * $this->after, fn() => $call());
            }
        } else {
            $begin = $this->space < 1 ? 1 : $this->space - (time() + 28800) % $this->space;
            loger(date('Y-m-d H:i:s', time() + $begin) . " 后每隔 " . $this->space . " 秒循环执行 {$this->name}");
            Timer::after(1000 * $begin, function () use ($call) {
                $this->after == 0 ? $call() : Timer::after(1000 * $this->after, fn() => $call());
                
                Timer::tick((int) (1000 * $this->space), fn() => $this->after == 0 ? $call() : Timer::after(1000 * $this->after, fn() => $call()));
            });
        }
    }

}
